package com.jzxk.handler.pay.wxpay;

import com.jzxk.tool.HttpInvoker;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.*;

/**
 * @author 今朝惜客
 * @CreateTime : 16/9/13 下午4:19
 * @Description : 微信支付
 */

@Component
public class WXPayHandler {

	private static final Logger LOG= LoggerFactory.getLogger(WXPayHandler.class);

	@Value("${wxpay.appId}")
	private String appId;//微信开放平台审核通过的应用APPID

	@Value("${wxpay.mchId}")
	private String mchId;//微信支付分配的商户号

	@Value("${wxpay.key}")
	private String key;//签名密钥

	//@Value("${wxpay.prepareUrl}")
	private String prepareUrl;

	//@Value("${wxpay.queryUrl}")
	private String queryUrl;

	//@Value("${wxpay.refundUrl}")
	private String refundUrl;

	@Value("${wxpay.refundQueryUrl}")
	private String refundQueryUrl;

	//@Value("${wxpay.mchPassword}")
	private String mchPassword;// 证书密码，默认为商户

	//@Value("${wxpay.certDir}")
	private String certDir;// 加密相关文件文件夹

	//@Value("${wxpay.notifyUrl}")
	private String notifyUrl;// 查询支付通知网关URL

	/**
	 * 退款状态查询
	 * @param outCode 微信生成的退款单号，在申请退款接口有返回
	 * @param innerCode 平台退款单号
	 */
	public void refundStateQuery(String outCode,String innerCode){

		SortedMap<String,String> requestMap=new TreeMap<String, String>();

		requestMap.put("appid",appId);
		requestMap.put("mch_id",mchId);
		requestMap.put("nonce_str",WXPayUtils.getNonceStr());

		if(StringUtils.isNotBlank(outCode)){
			requestMap.put("refund_id", outCode);
		}else{
			requestMap.put("out_refund_no", innerCode);
		}

		String sign = WXPayUtils.createSign(requestMap,key);

		StringBuffer sb = new StringBuffer();
		Set<Map.Entry<String, String>> es = requestMap.entrySet();
		Iterator<Map.Entry<String, String>> it = es.iterator();
		while (it.hasNext()) {
			Map.Entry<String, String> entry = it.next();
			String key = entry.getKey();
			String value = entry.getValue();
			sb.append(String.format("<%s>%s</%s>", key, value, key));
		}

		// 去掉最后一个&
		String postData = "<xml>" + sb.append(String.format("<sign>%s</sign>", sign)).toString() + "</xml>";

		LOG.info("退款查询数据{}",postData);

		try {

			String resContent = HttpInvoker.httpsPost(refundQueryUrl, null, postData, null);
			LOG.info("退款查询应答{}",resContent);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}


}
